import csv
import requests
import os
import re

# 创建文件夹
path = os.getcwd() + '/images'
if not os.path.exists(path):
    os.mkdir(path)

def fun1():
    # 打开文件
    with open('Jobone.csv', 'r') as file:
        reader = csv.reader(file)
        # 遍历每一行数据
        for row in reader:
            # 处理每一行数据
            school = row[0]
            logo_sq = row[1]
            logo_rec = row[2]
            download_image(school + "正方形", logo_sq)
            download_image(school + "长方形", logo_rec)

# 下载图片
def download_image(title, cover):
    # 请求头
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 SLBrowser/9.0.3.1311 SLBChan/105',
    }
    res = requests.get(cover, headers=headers)

    # 判断标题是否含有\/:*?"<>|，文件命名不能含有这些，如果有，则用下划线_取代
    new_title = validateTitle(title)
    with open(path + '/' + new_title + '.jpg', mode='wb') as f:
        # 图片内容写入文件
        f.write(res.content)
        print(f"正在下载图片，图片名：{title}.jpg")

# 去除文件中的非法字符(正则表达式)
def validateTitle(title):
    pattern = r"[\\\/\:\*\?\"\<\>\|]"
    new_title = re.sub(pattern, '_', title)
    return new_title

if __name__ == '__main__':
    fun1()